package com.harmontronics.hanma.paas.paas.domain.app.service.tools;

import com.harmontronics.hanma.paas.paas.utils.OkHttpUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.Map;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;

/**
 * @author ldb
 */
@Service("httpClient")
@Scope(SCOPE_PROTOTYPE)
public class HttpClient {

    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private HttpServiceHelper httpServiceHelper;

    private String serviceKey;

    private String path;

    private Map<String, Object> params;

    public HttpClient with(String serviceKey, String path, Map<String, Object> params) {
        this.serviceKey = serviceKey;
        this.params = params;
        this.path = path;
        return this;
    }


    public String getToken() {
        Assert.notNull(serviceKey,"未设置serviceKey");
        return httpServiceHelper.getToken(serviceKey);
    }


    public String getFullPath() {
        Assert.notNull(serviceKey,"未设置serviceKey");
        Assert.notNull(path,"未设置path");
        return httpServiceHelper.getReqUrl(serviceKey, path);
    }

    public Object execute(Request.Builder builder) throws IOException {
        return OkHttpUtils.execNewCall(okHttpClient, builder.build());
    }
}
